package controller.day04;

import entity.User;
import service.UserService;
import service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "SaveUserServlet", value = "/SaveUserServlet")
public class SaveUserServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 获得用户录入的数据
        String username =  request.getParameter("username");
        String password =  request.getParameter("password");
        String powerStr =  request.getParameter("power");  // 0 / 1
        Integer power = Integer.valueOf(powerStr);

        System.out.println("name =" + username);
        System.out.println("password =" + password);
        System.out.println("power =" + power);

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setPower(power);

        //2. 调用service ，添加新用户
        boolean result = userService.save(user);

        //3. 添加成功，跳转到 成功页面， 若添加失败，跳转到index.jsp
        if(result){
            request.setAttribute("msg","添加新用户成功");
            request.getRequestDispatcher("/day04/success.jsp").forward(request,response);
        }else{
            request.setAttribute("msg","添加新用户失败");
            request.getRequestDispatcher("/day04/index.jsp").forward(request,response);
        }
    }
}
